package com.hfzy.ihk.common.core.mybatis.myTypeHandler;

import com.hfzy.ihk.common.core.mybatis.EnumUtils;
import com.hfzy.ihk.common.facade.CustomEnumType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * Created by Administrator on 2018/12/26.
 * 这个比较特殊，为了不用修改mybatisplus的源码，所以就放在com.hfzy.ihk.common.core.mybatis.typeHandler目录之外。避免
 * mybatis-plus扫描到报错
 * @author wws
 */
public class CustomEnumTypeEnumHandler <E extends Enum<?> & CustomEnumType> extends BaseTypeHandler<CustomEnumType> {

    private Class<E> type;

    public CustomEnumTypeEnumHandler(Class<E> type) {
        if (Objects.isNull(type)) {
            throw new IllegalArgumentException("type should not be null.");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, CustomEnumType parameter, JdbcType jdbcType)
            throws SQLException {
        if (jdbcType == null) {
            ps.setObject(i, parameter.getValue());
        } else {
            ps.setObject(i, parameter.getValue(), jdbcType.TYPE_CODE);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (null == rs.getString(columnName) && rs.wasNull()) {
            return null;
        }
        return EnumUtils.valueOf(type, rs.getObject(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (null == rs.getString(columnIndex) && rs.wasNull()) {
            return null;
        }
        return EnumUtils.valueOf(type, rs.getObject(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (null == cs.getString(columnIndex) && cs.wasNull()) {
            return null;
        }
        return EnumUtils.valueOf(type, cs.getObject(columnIndex));
    }
}
